﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.IdentityModel;
using System.IdentityModel;
using System.IdentityModel.Tokens;
using System.Web.UI.WebControls;
using Microsoft.IdentityModel.Claims;

namespace WindowsSignInPage
{
    public class AutoLoginModel : IHttpModule
    {

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_SPBeginRequest);
        }

        /// <summary>
        /// /progressbar.aspx page set username for swfupload
        /// </summary>
        protected string UploadUser
        {
            get
            {
                return Context.Request.QueryString["username"];
            }
        }

        bool IsUploadPagePost
        {
            get
            {
                if (Context.Request.RequestType.ToLower() == "post" && 
                    (Context.Request.Url.AbsoluteUri.ToLower().Contains("/progressbar.aspx") ||
                    Context.Request.Url.AbsoluteUri.ToLower().Contains("/upload.aspx")
                    ))
                    return true;
                return false;

            }
        }

        private void UploadLog()
        {
            string contextType = Context.Request.ContentType;
            if (contextType.ToLower().Contains("multipart/form-data") && Context.Request.Files.Count > 0)
            {
                List<string> fileList = new List<string>();
                for (int i = 0; i < Context.Request.Files.Count; i++)
                {
                    fileList.Add(Context.Request.Files[i].FileName);
                }
                Authentication.LogUploadFile(fileList.ToArray());
            }
        }

        void context_SPBeginRequest(object sender, EventArgs e)
        {
            try
            {
                if (Context.Request.Url.AbsoluteUri.ToLower().Contains("/_windows/default.aspx"))
                    return;

                string currentUser = Authentication.GetCurrentUser();

                if (IsUploadPagePost)
                {
                    currentUser = UploadUser;
                   
                }

                if (string.IsNullOrEmpty(currentUser))
                {
                    string logonUrl = Authentication.GetLogonUrl();
                    Context.Response.Redirect(logonUrl);
                }
                else
                {
                    //if (!Authentication.IsAuthed)
                    //{
                    LoginUser loginUser = new LoginUser(currentUser);

                    if (!string.IsNullOrEmpty(loginUser.Pwd))
                    {
                        string password = EncryptTool.Decrypt(loginUser.Pwd);
                        if (WindowsContext.Instance.ImpersonateValidUser(loginUser.LoginId, loginUser.Domain, password))
                        {
                            Authentication.SuccessLogin(loginUser.LoginId, password);
                            //Authentication.LogLogin();
                        }
                        else
                        {
                            SPUtility.Redirect("/_windows/default.aspx", SPRedirectFlags.Default, Context);
                        }

                    }
                    else
                    {
                        Authentication.RemoveCookiesAndSignOut();
                    }
                        //Context.Response.Redirect("/_windows/default.aspx");
                        //SPUtility.Redirect("/_windows/default.aspx", SPRedirectFlags.Default, Context);
                    //}
                    UploadLog();
                }
            }
            catch (Exception ex)
            {
                Logger.Error("SPHttpModel error.", ex);
            }
        }

       

        protected HttpContext Context
        {
            get { return HttpContext.Current; }
        }
       
    }
}